package com.xuhai.blog.admin.controller;

import com.xuhai.blog.admin.entity.CodeEntity;
import com.xuhai.blog.admin.entity.UserEntity;
import com.xuhai.blog.admin.service.CodeService;
import com.xuhai.blog.admin.service.ExpiresService;
import com.xuhai.blog.admin.service.UserService;
import com.xuhai.blog.common.form.LoginForm;
import com.xuhai.blog.common.util.ResultJson;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;


/**
 * @Author PangJunjie
 * @Date 2022/2/8/008
 */
@RestController
@RequestMapping("/admin")
public class LoginController extends AbstractController {

    @Autowired
    private CodeService codeService;

    @Autowired
    private UserService userService;

    @Autowired
    private ExpiresService expiresService;

    @GetMapping("/kaptcha.jpg")
    public void kaptcha(HttpServletResponse response,String uuid) throws Exception {
        /*设置输出头*/
        response.setHeader("Cache-Control","no-store, no-cache");
        response.setContentType("image/jpeg");
        /*获取生成的图片*/
        BufferedImage image=codeService.getKaptcha(uuid);
        /*获取输出流*/
        ServletOutputStream out= response.getOutputStream();
        /*输出图片*/
        ImageIO.write(image,"jpg",out);
        /*关闭流*/
        IOUtils.closeQuietly(out);
    }


    @PostMapping("/login")
    public ResultJson login(@RequestBody LoginForm loginForm){
        return userService.login(loginForm);
    }

    @PostMapping("/logout")
    public ResultJson logout(){
        expiresService.logout(getUserId());
        return ResultJson.ok();
    }
}
